// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 得分
let score = 0;
const scoreElement = document.getElementById('score');

// 足球属性
const BALL_RADIUS = 20;
let ballX = CANVAS_WIDTH / 2;
let ballY = CANVAS_HEIGHT / 2;
let ballDx = 0;
let ballDy = 0;
const FRICTION = 0.98;

// 球门属性
const GOAL_WIDTH = 150;
const GOAL_HEIGHT = 30;
const GOAL_X = (CANVAS_WIDTH - GOAL_WIDTH) / 2;
const GOAL_Y = 0;

// 绘制足球
function drawBall() {
    ctx.beginPath();
    ctx.arc(ballX, ballY, BALL_RADIUS, 0, Math.PI * 2);
    ctx.fillStyle = 'white';
    ctx.fill();
    ctx.closePath();
}

// 绘制球门
function drawGoal() {
    ctx.beginPath();
    ctx.rect(GOAL_X, GOAL_Y, GOAL_WIDTH, GOAL_HEIGHT);
    ctx.fillStyle = 'red';
    ctx.fill();
    ctx.closePath();
}

// 移动足球
function moveBall() {
    ballX += ballDx;
    ballY += ballDy;

    // 摩擦力效果
    ballDx *= FRICTION;
    ballDy *= FRICTION;

    // 边界检测
    if (ballX - BALL_RADIUS < 0 || ballX + BALL_RADIUS > CANVAS_WIDTH) {
        ballDx = -ballDx;
    }
    if (ballY - BALL_RADIUS < 0 || ballY + BALL_RADIUS > CANVAS_HEIGHT) {
        ballDy = -ballDy;
    }

    // 检查是否进球
    if (
        ballX > GOAL_X &&
        ballX < GOAL_X + GOAL_WIDTH &&
        ballY - BALL_RADIUS < GOAL_Y + GOAL_HEIGHT
    ) {
        score++;
        scoreElement.textContent = score;
        // 重置足球位置
        ballX = CANVAS_WIDTH / 2;
        ballY = CANVAS_HEIGHT / 2;
        ballDx = 0;
        ballDy = 0;
    }
}

// 处理鼠标点击，踢球
canvas.addEventListener('click', function (event) {
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    const dx = mouseX - ballX;
    const dy = mouseY - ballY;
    const force = 0.2;
    ballDx = dx * force;
    ballDy = dy * force;
});

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawBall();
    drawGoal();
    moveBall();

    requestAnimationFrame(gameLoop);
}

// 初始化游戏
gameLoop();